3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\Permissions\PermissionManager
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use MediaWiki\Linker\LinkTarget
;
29 use MediaWiki\Interwiki\InterwikiLookup
;
30 use MediaWiki\MediaWikiServices
;
33 * Represents a title within MediaWiki.
34 * Optionally may contain an interwiki designation or namespace.
35 * @note This class can fetch various kinds of data from the database;
36 * however, it does so inefficiently.
37 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
38 * and does not rely on global state or the database.
40 class Title
implements LinkTarget
, IDBAccessObject
{
41 /** @var MapCacheLRU|null */
42 private static $titleCache = null;
45 * Title::newFromText maintains a cache to avoid expensive re-normalization of
46 * commonly used titles. On a batch operation this can become a memory leak
47 * if not bounded. After hitting this many titles reset the cache.
49 const CACHE_MAX
= 1000;
52 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
53 * to use the master DB
55 const GAID_FOR_UPDATE
= 1;
58 * Flag for use with factory methods like newFromLinkTarget() that have
59 * a $forceClone parameter. If set, the method must return a new instance.
60 * Without this flag, some factory methods may return existing instances.
62 const NEW_CLONE
= 'clone';
65 * @name Private member variables
66 * Please use the accessor functions instead.
71 /** @var string Text form (spaces not underscores) of the main part */
72 public $mTextform = '';
74 /** @var string URL-encoded form of the main part */
75 public $mUrlform = '';
77 /** @var string Main part with underscores */
78 public $mDbkeyform = '';
80 /** @var string Database key with the initial letter in the case specified by the user */
81 protected $mUserCaseDBKey;
83 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
84 public $mNamespace = NS_MAIN
;
86 /** @var string Interwiki prefix */
87 public $mInterwiki = '';
89 /** @var bool Was this Title created from a string with a local interwiki prefix? */
90 private $mLocalInterwiki = false;
92 /** @var string Title fragment (i.e. the bit after the #) */
93 public $mFragment = '';
95 /** @var int Article ID, fetched from the link cache on demand */
96 public $mArticleID = -1;
98 /** @var bool|int ID of most recent revision */
99 protected $mLatestID = false;
102 * @var bool|string ID of the page's content model, i.e. one of the
103 * CONTENT_MODEL_XXX constants
105 private $mContentModel = false;
108 * @var bool If a content model was forced via setContentModel()
109 * this will be true to avoid having other code paths reset it
111 private $mForcedContentModel = false;
113 /** @var int Estimated number of revisions; null of not loaded */
114 private $mEstimateRevisions;
116 /** @var array Array of groups allowed to edit this article */
117 public $mRestrictions = [];
120 * @var string|bool Comma-separated set of permission keys
121 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
122 * Edit and move sections are separated by a colon
123 * Example: "edit=autoconfirmed,sysop:move=sysop"
125 protected $mOldRestrictions = false;
127 /** @var bool Cascade restrictions on this page to included templates and images? */
128 public $mCascadeRestriction;
130 /** Caching the results of getCascadeProtectionSources */
131 public $mCascadingRestrictions;
133 /** @var array When do the restrictions on this page expire? */
134 protected $mRestrictionsExpiry = [];
136 /** @var bool Are cascading restrictions in effect on this page? */
137 protected $mHasCascadingRestrictions;
139 /** @var array Where are the cascading restrictions coming from on this page? */
140 public $mCascadeSources;
142 /** @var bool Boolean for initialisation on demand */
143 public $mRestrictionsLoaded = false;
146 * Text form including namespace/interwiki, initialised on demand
148 * Only public to share cache with TitleFormatter
153 public $prefixedText = null;
155 /** @var mixed Cached value for getTitleProtection (create protection) */
156 public $mTitleProtection;
159 * @var int Namespace index when there is no namespace. Don't change the
160 * following default, NS_MAIN is hardcoded in several places. See T2696.
161 * Zero except in {{transclusion}} tags.
163 public $mDefaultNamespace = NS_MAIN
;
165 /** @var int The page length, 0 for special pages */
166 protected $mLength = -1;
168 /** @var null Is the article at this title a redirect? */
169 public $mRedirect = null;
171 /** @var array Associative array of user ID -> timestamp/false */
172 private $mNotificationTimestamp = [];
174 /** @var bool Whether a page has any subpages */
175 private $mHasSubpages;
177 /** @var bool The (string) language code of the page's language and content code. */
178 private $mPageLanguage = false;
180 /** @var string|bool|null The page language code from the database, null if not saved in
181 * the database or false if not loaded, yet. */
182 private $mDbPageLanguage = false;
184 /** @var TitleValue|null A corresponding TitleValue object */
185 private $mTitleValue = null;
187 /** @var bool|null Would deleting this page be a big deletion? */
188 private $mIsBigDeletion = null;
192 * B/C kludge: provide a TitleParser for use by Title.
193 * Ideally, Title would have no methods that need this.
194 * Avoid usage of this singleton by using TitleValue
195 * and the associated services when possible.
197 * @return TitleFormatter
199 private static function getTitleFormatter() {
200 return MediaWikiServices
::getInstance()->getTitleFormatter();
204 * B/C kludge: provide an InterwikiLookup for use by Title.
205 * Ideally, Title would have no methods that need this.
206 * Avoid usage of this singleton by using TitleValue
207 * and the associated services when possible.
209 * @return InterwikiLookup
211 private static function getInterwikiLookup() {
212 return MediaWikiServices
::getInstance()->getInterwikiLookup();
218 function __construct() {
222 * Create a new Title from a prefixed DB key
224 * @param string $key The database key, which has underscores
225 * instead of spaces, possibly including namespace and
227 * @return Title|null Title, or null on an error
229 public static function newFromDBkey( $key ) {
231 $t->mDbkeyform
= $key;
234 $t->secureAndSplit();
236 } catch ( MalformedTitleException
$ex ) {
242 * Returns a Title given a TitleValue.
243 * If the given TitleValue is already a Title instance, that instance is returned,
244 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
245 * is already a Title instance, that instance is copied using the clone operator.
247 * @param TitleValue $titleValue Assumed to be safe.
248 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
252 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
253 return self
::newFromLinkTarget( $titleValue, $forceClone );
257 * Returns a Title given a LinkTarget.
258 * If the given LinkTarget is already a Title instance, that instance is returned,
259 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
260 * is already a Title instance, that instance is copied using the clone operator.
262 * @param LinkTarget $linkTarget Assumed to be safe.
263 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
267 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
268 if ( $linkTarget instanceof Title
) {
269 // Special case if it's already a Title object
270 if ( $forceClone === self
::NEW_CLONE
) {
271 return clone $linkTarget;
276 return self
::makeTitle(
277 $linkTarget->getNamespace(),
278 $linkTarget->getText(),
279 $linkTarget->getFragment(),
280 $linkTarget->getInterwiki()
285 * Create a new Title from text, such as what one would find in a link. De-
286 * codes any HTML entities in the text.
288 * Title objects returned by this method are guaranteed to be valid, and
289 * thus return true from the isValid() method.
291 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
292 * It may instead be a cached instance created previously, with references to it remaining
295 * @param string|int|null $text The link text; spaces, prefixes, and an
296 * initial ':' indicating the main namespace are accepted.
297 * @param int $defaultNamespace The namespace to use if none is specified
298 * by a prefix. If you want to force a specific namespace even if
299 * $text might begin with a namespace prefix, use makeTitle() or
301 * @throws InvalidArgumentException
302 * @return Title|null Title or null on an error.
304 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
305 // DWIM: Integers can be passed in here when page titles are used as array keys.
306 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
307 throw new InvalidArgumentException( '$text must be a string.' );
309 if ( $text === null ) {
314 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
315 } catch ( MalformedTitleException
$ex ) {
321 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
322 * rather than returning null.
324 * The exception subclasses encode detailed information about why the title is invalid.
326 * Title objects returned by this method are guaranteed to be valid, and
327 * thus return true from the isValid() method.
329 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
330 * It may instead be a cached instance created previously, with references to it remaining
333 * @see Title::newFromText
336 * @param string $text Title text to check
337 * @param int $defaultNamespace
338 * @throws MalformedTitleException If the title is invalid
341 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
342 if ( is_object( $text ) ) {
343 throw new MWException( '$text must be a string, given an object' );
344 } elseif ( $text === null ) {
345 // Legacy code relies on MalformedTitleException being thrown in this case
346 // (happens when URL with no title in it is parsed). TODO fix
347 throw new MalformedTitleException( 'title-invalid-empty' );
350 $titleCache = self
::getTitleCache();
352 // Wiki pages often contain multiple links to the same page.
353 // Title normalization and parsing can become expensive on pages with many
354 // links, so we can save a little time by caching them.
355 // In theory these are value objects and won't get changed...
356 if ( $defaultNamespace == NS_MAIN
) {
357 $t = $titleCache->get( $text );
363 // Convert things like é ā or 〗 into normalized (T16952) text
364 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
367 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
368 $t->mDefaultNamespace
= (int)$defaultNamespace;
370 $t->secureAndSplit();
371 if ( $defaultNamespace == NS_MAIN
) {
372 $titleCache->set( $text, $t );
378 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
380 * Example of wrong and broken code:
381 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
383 * Example of right code:
384 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
386 * Create a new Title from URL-encoded text. Ensures that
387 * the given title's length does not exceed the maximum.
389 * @param string $url The title, as might be taken from a URL
390 * @return Title|null The new object, or null on an error
392 public static function newFromURL( $url ) {
395 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
396 # but some URLs used it as a space replacement and they still come
397 # from some external search tools.
398 if ( strpos( self
::legalChars(), '+' ) === false ) {
399 $url = strtr( $url, '+', ' ' );
402 $t->mDbkeyform
= strtr( $url, ' ', '_' );
405 $t->secureAndSplit();
407 } catch ( MalformedTitleException
$ex ) {
413 * @return MapCacheLRU
415 private static function getTitleCache() {
416 if ( self
::$titleCache === null ) {
417 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
419 return self
::$titleCache;
423 * Returns a list of fields that are to be selected for initializing Title
424 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
425 * whether to include page_content_model.
429 protected static function getSelectFields() {
430 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
433 'page_namespace', 'page_title', 'page_id',
434 'page_len', 'page_is_redirect', 'page_latest',
437 if ( $wgContentHandlerUseDB ) {
438 $fields[] = 'page_content_model';
441 if ( $wgPageLanguageUseDB ) {
442 $fields[] = 'page_lang';
449 * Create a new Title from an article ID
451 * @param int $id The page_id corresponding to the Title to create
452 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
453 * @return Title|null The new object, or null on an error
455 public static function newFromID( $id, $flags = 0 ) {
456 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
457 $row = $db->selectRow(
459 self
::getSelectFields(),
460 [ 'page_id' => $id ],
463 if ( $row !== false ) {
464 $title = self
::newFromRow( $row );
473 * Make an array of titles from an array of IDs
475 * @param int[] $ids Array of IDs
476 * @return Title[] Array of Titles
478 public static function newFromIDs( $ids ) {
479 if ( !count( $ids ) ) {
482 $dbr = wfGetDB( DB_REPLICA
);
486 self
::getSelectFields(),
487 [ 'page_id' => $ids ],
492 foreach ( $res as $row ) {
493 $titles[] = self
::newFromRow( $row );
499 * Make a Title object from a DB row
501 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
502 * @return Title Corresponding Title
504 public static function newFromRow( $row ) {
505 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
506 $t->loadFromRow( $row );
511 * Load Title object fields from a DB row.
512 * If false is given, the title will be treated as non-existing.
514 * @param stdClass|bool $row Database row
516 public function loadFromRow( $row ) {
517 if ( $row ) { // page found
518 if ( isset( $row->page_id
) ) {
519 $this->mArticleID
= (int)$row->page_id
;
521 if ( isset( $row->page_len
) ) {
522 $this->mLength
= (int)$row->page_len
;
524 if ( isset( $row->page_is_redirect
) ) {
525 $this->mRedirect
= (bool)$row->page_is_redirect
;
527 if ( isset( $row->page_latest
) ) {
528 $this->mLatestID
= (int)$row->page_latest
;
530 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
531 $this->mContentModel
= (string)$row->page_content_model
;
532 } elseif ( !$this->mForcedContentModel
) {
533 $this->mContentModel
= false; # initialized lazily in getContentModel()
535 if ( isset( $row->page_lang
) ) {
536 $this->mDbPageLanguage
= (string)$row->page_lang
;
538 if ( isset( $row->page_restrictions
) ) {
539 $this->mOldRestrictions
= $row->page_restrictions
;
541 } else { // page not found
542 $this->mArticleID
= 0;
544 $this->mRedirect
= false;
545 $this->mLatestID
= 0;
546 if ( !$this->mForcedContentModel
) {
547 $this->mContentModel
= false; # initialized lazily in getContentModel()
553 * Create a new Title from a namespace index and a DB key.
555 * It's assumed that $ns and $title are safe, for instance when
556 * they came directly from the database or a special page name,
557 * not from user input.
559 * No validation is applied. For convenience, spaces are normalized
560 * to underscores, so that e.g. user_text fields can be used directly.
562 * @note This method may return Title objects that are "invalid"
563 * according to the isValid() method. This is usually caused by
564 * configuration changes: e.g. a namespace that was once defined is
565 * no longer configured, or a character that was once allowed in
566 * titles is now forbidden.
568 * @param int $ns The namespace of the article
569 * @param string $title The unprefixed database key form
570 * @param string $fragment The link fragment (after the "#")
571 * @param string $interwiki The interwiki prefix
572 * @return Title The new object
574 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
576 $t->mInterwiki
= $interwiki;
577 $t->mFragment
= $fragment;
578 $t->mNamespace
= $ns = (int)$ns;
579 $t->mDbkeyform
= strtr( $title, ' ', '_' );
580 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
581 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
582 $t->mTextform
= strtr( $title, '_', ' ' );
583 $t->mContentModel
= false; # initialized lazily in getContentModel()
588 * Create a new Title from a namespace index and a DB key.
589 * The parameters will be checked for validity, which is a bit slower
590 * than makeTitle() but safer for user-provided data.
592 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
593 * that is, they return true from the isValid() method. If no valid Title
594 * can be constructed from the input, this method returns null.
596 * @param int $ns The namespace of the article
597 * @param string $title Database key form
598 * @param string $fragment The link fragment (after the "#")
599 * @param string $interwiki Interwiki prefix
600 * @return Title|null The new object, or null on an error
602 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
603 // NOTE: ideally, this would just call makeTitle() and then isValid(),
604 // but presently, that means more overhead on a potential performance hotspot.
606 if ( !MWNamespace
::exists( $ns ) ) {
611 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
614 $t->secureAndSplit();
616 } catch ( MalformedTitleException
$ex ) {
622 * Create a new Title for the Main Page
624 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
625 * It may instead be a cached instance created previously, with references to it remaining
628 * @return Title The new object
630 public static function newMainPage() {
631 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
632 // Don't give fatal errors if the message is broken
634 $title = self
::newFromText( 'Main Page' );
640 * Get the prefixed DB key associated with an ID
642 * @param int $id The page_id of the article
643 * @return Title|null An object representing the article, or null if no such article was found
645 public static function nameOf( $id ) {
646 $dbr = wfGetDB( DB_REPLICA
);
648 $s = $dbr->selectRow(
650 [ 'page_namespace', 'page_title' ],
651 [ 'page_id' => $id ],
654 if ( $s === false ) {
658 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
663 * Get a regex character class describing the legal characters in a link
665 * @return string The list of characters, not delimited
667 public static function legalChars() {
668 global $wgLegalTitleChars;
669 return $wgLegalTitleChars;
673 * Utility method for converting a character sequence from bytes to Unicode.
675 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
676 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
678 * @param string $byteClass
681 public static function convertByteClassToUnicodeClass( $byteClass ) {
682 $length = strlen( $byteClass );
684 $x0 = $x1 = $x2 = '';
686 $d0 = $d1 = $d2 = '';
687 // Decoded integer codepoints
688 $ord0 = $ord1 = $ord2 = 0;
690 $r0 = $r1 = $r2 = '';
694 $allowUnicode = false;
695 for ( $pos = 0; $pos < $length; $pos++
) {
696 // Shift the queues down
705 // Load the current input token and decoded values
706 $inChar = $byteClass[$pos];
707 if ( $inChar == '\\' ) {
708 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
709 $x0 = $inChar . $m[0];
710 $d0 = chr( hexdec( $m[1] ) );
711 $pos +
= strlen( $m[0] );
712 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
713 $x0 = $inChar . $m[0];
714 $d0 = chr( octdec( $m[0] ) );
715 $pos +
= strlen( $m[0] );
716 } elseif ( $pos +
1 >= $length ) {
719 $d0 = $byteClass[$pos +
1];
727 // Load the current re-encoded value
728 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
729 $r0 = sprintf( '\x%02x', $ord0 );
730 } elseif ( $ord0 >= 0x80 ) {
731 // Allow unicode if a single high-bit character appears
732 $r0 = sprintf( '\x%02x', $ord0 );
733 $allowUnicode = true;
734 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
740 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
742 if ( $ord2 > $ord0 ) {
744 } elseif ( $ord0 >= 0x80 ) {
746 $allowUnicode = true;
747 if ( $ord2 < 0x80 ) {
748 // Keep the non-unicode section of the range
755 // Reset state to the initial value
756 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
757 } elseif ( $ord2 < 0x80 ) {
762 if ( $ord1 < 0x80 ) {
765 if ( $ord0 < 0x80 ) {
768 if ( $allowUnicode ) {
769 $out .= '\u0080-\uFFFF';
775 * Make a prefixed DB key from a DB key and a namespace index
777 * @param int $ns Numerical representation of the namespace
778 * @param string $title The DB key form the title
779 * @param string $fragment The link fragment (after the "#")
780 * @param string $interwiki The interwiki prefix
781 * @param bool $canonicalNamespace If true, use the canonical name for
782 * $ns instead of the localized version.
783 * @return string The prefixed form of the title
785 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
786 $canonicalNamespace = false
788 if ( $canonicalNamespace ) {
789 $namespace = MWNamespace
::getCanonicalName( $ns );
791 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
793 $name = $namespace == '' ?
$title : "$namespace:$title";
794 if ( strval( $interwiki ) != '' ) {
795 $name = "$interwiki:$name";
797 if ( strval( $fragment ) != '' ) {
798 $name .= '#' . $fragment;
804 * Callback for usort() to do title sorts by (namespace, title)
806 * @param LinkTarget $a
807 * @param LinkTarget $b
809 * @return int Result of string comparison, or namespace comparison
811 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
812 return $a->getNamespace() <=> $b->getNamespace()
813 ?
: strcmp( $a->getText(), $b->getText() );
817 * Returns true if the title is valid, false if it is invalid.
819 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
820 * Invalid titles may get returned from makeTitle(), and it may be useful to
821 * allow them to exist, e.g. in order to process log entries about pages in
822 * namespaces that belong to extensions that are no longer installed.
824 * @note This method is relatively expensive. When constructing Title
825 * objects that need to be valid, use an instantiator method that is guaranteed
826 * to return valid titles, such as makeTitleSafe() or newFromText().
830 public function isValid() {
831 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
836 $parser = MediaWikiServices
::getInstance()->getTitleParser();
837 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
839 } catch ( MalformedTitleException
$ex ) {
845 * Determine whether the object refers to a page within
846 * this project (either this wiki or a wiki with a local
847 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
849 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
851 public function isLocal() {
852 if ( $this->isExternal() ) {
853 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
855 return $iw->isLocal();
862 * Is this Title interwiki?
866 public function isExternal() {
867 return $this->mInterwiki
!== '';
871 * Get the interwiki prefix
873 * Use Title::isExternal to check if a interwiki is set
875 * @return string Interwiki prefix
877 public function getInterwiki() {
878 return $this->mInterwiki
;
882 * Was this a local interwiki link?
886 public function wasLocalInterwiki() {
887 return $this->mLocalInterwiki
;
891 * Determine whether the object refers to a page within
892 * this project and is transcludable.
894 * @return bool True if this is transcludable
896 public function isTrans() {
897 if ( !$this->isExternal() ) {
901 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
905 * Returns the DB name of the distant wiki which owns the object.
907 * @return string|false The DB name
909 public function getTransWikiID() {
910 if ( !$this->isExternal() ) {
914 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
918 * Get a TitleValue object representing this Title.
920 * @note Not all valid Titles have a corresponding valid TitleValue
921 * (e.g. TitleValues cannot represent page-local links that have a
922 * fragment but no title text).
924 * @return TitleValue|null
926 public function getTitleValue() {
927 if ( $this->mTitleValue
=== null ) {
929 $this->mTitleValue
= new TitleValue(
935 } catch ( InvalidArgumentException
$ex ) {
936 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
937 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
941 return $this->mTitleValue
;
945 * Get the text form (spaces not underscores) of the main part
947 * @return string Main part of the title
949 public function getText() {
950 return $this->mTextform
;
954 * Get the URL-encoded form of the main part
956 * @return string Main part of the title, URL-encoded
958 public function getPartialURL() {
959 return $this->mUrlform
;
963 * Get the main part with underscores
965 * @return string Main part of the title, with underscores
967 public function getDBkey() {
968 return $this->mDbkeyform
;
972 * Get the DB key with the initial letter case as specified by the user
973 * @deprecated since 1.33; please use Title::getDBKey() instead
975 * @return string DB key
977 function getUserCaseDBKey() {
978 if ( !is_null( $this->mUserCaseDBKey
) ) {
979 return $this->mUserCaseDBKey
;
981 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
982 return $this->mDbkeyform
;
987 * Get the namespace index, i.e. one of the NS_xxxx constants.
989 * @return int Namespace index
991 public function getNamespace() {
992 return $this->mNamespace
;
996 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
998 * @todo Deprecate this in favor of SlotRecord::getModel()
1000 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1001 * @return string Content model id
1003 public function getContentModel( $flags = 0 ) {
1004 if ( !$this->mForcedContentModel
1005 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1006 && $this->getArticleID( $flags )
1008 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1009 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1010 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1013 if ( !$this->mContentModel
) {
1014 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1017 return $this->mContentModel
;
1021 * Convenience method for checking a title's content model name
1023 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1024 * @return bool True if $this->getContentModel() == $id
1026 public function hasContentModel( $id ) {
1027 return $this->getContentModel() == $id;
1031 * Set a proposed content model for the page for permissions
1032 * checking. This does not actually change the content model
1035 * Additionally, you should make sure you've checked
1036 * ContentHandler::canBeUsedOn() first.
1039 * @param string $model CONTENT_MODEL_XXX constant
1041 public function setContentModel( $model ) {
1042 $this->mContentModel
= $model;
1043 $this->mForcedContentModel
= true;
1047 * Get the namespace text
1049 * @return string|false Namespace text
1051 public function getNsText() {
1052 if ( $this->isExternal() ) {
1053 // This probably shouldn't even happen, except for interwiki transclusion.
1054 // If possible, use the canonical name for the foreign namespace.
1055 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1056 if ( $nsText !== false ) {
1062 $formatter = self
::getTitleFormatter();
1063 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1064 } catch ( InvalidArgumentException
$ex ) {
1065 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1071 * Get the namespace text of the subject (rather than talk) page
1073 * @return string Namespace text
1075 public function getSubjectNsText() {
1076 return MediaWikiServices
::getInstance()->getContentLanguage()->
1077 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1081 * Get the namespace text of the talk page
1083 * @return string Namespace text
1085 public function getTalkNsText() {
1086 return MediaWikiServices
::getInstance()->getContentLanguage()->
1087 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1091 * Can this title have a corresponding talk page?
1093 * @see MWNamespace::hasTalkNamespace
1096 * @return bool True if this title either is a talk page or can have a talk page associated.
1098 public function canHaveTalkPage() {
1099 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1103 * Is this in a namespace that allows actual pages?
1107 public function canExist() {
1108 return $this->mNamespace
>= NS_MAIN
;
1112 * Can this title be added to a user's watchlist?
1116 public function isWatchable() {
1117 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1121 * Returns true if this is a special page.
1125 public function isSpecialPage() {
1126 return $this->mNamespace
== NS_SPECIAL
;
1130 * Returns true if this title resolves to the named special page
1132 * @param string $name The special page name
1135 public function isSpecial( $name ) {
1136 if ( $this->isSpecialPage() ) {
1137 list( $thisName, /* $subpage */ ) =
1138 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1139 resolveAlias( $this->mDbkeyform
);
1140 if ( $name == $thisName ) {
1148 * If the Title refers to a special page alias which is not the local default, resolve
1149 * the alias, and localise the name as necessary. Otherwise, return $this
1153 public function fixSpecialName() {
1154 if ( $this->isSpecialPage() ) {
1155 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1156 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1157 if ( $canonicalName ) {
1158 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1159 if ( $localName != $this->mDbkeyform
) {
1160 return self
::makeTitle( NS_SPECIAL
, $localName );
1168 * Returns true if the title is inside the specified namespace.
1170 * Please make use of this instead of comparing to getNamespace()
1171 * This function is much more resistant to changes we may make
1172 * to namespaces than code that makes direct comparisons.
1173 * @param int $ns The namespace
1177 public function inNamespace( $ns ) {
1178 return MWNamespace
::equals( $this->mNamespace
, $ns );
1182 * Returns true if the title is inside one of the specified namespaces.
1184 * @param int|int[] $namespaces,... The namespaces to check for
1188 public function inNamespaces( /* ... */ ) {
1189 $namespaces = func_get_args();
1190 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1191 $namespaces = $namespaces[0];
1194 foreach ( $namespaces as $ns ) {
1195 if ( $this->inNamespace( $ns ) ) {
1204 * Returns true if the title has the same subject namespace as the
1205 * namespace specified.
1206 * For example this method will take NS_USER and return true if namespace
1207 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1208 * as their subject namespace.
1210 * This is MUCH simpler than individually testing for equivalence
1211 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1216 public function hasSubjectNamespace( $ns ) {
1217 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1221 * Is this Title in a namespace which contains content?
1222 * In other words, is this a content page, for the purposes of calculating
1227 public function isContentPage() {
1228 return MWNamespace
::isContent( $this->mNamespace
);
1232 * Would anybody with sufficient privileges be able to move this page?
1233 * Some pages just aren't movable.
1237 public function isMovable() {
1238 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1239 // Interwiki title or immovable namespace. Hooks don't get to override here
1244 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1249 * Is this the mainpage?
1250 * @note Title::newFromText seems to be sufficiently optimized by the title
1251 * cache that we don't need to over-optimize by doing direct comparisons and
1252 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1253 * ends up reporting something differently than $title->isMainPage();
1258 public function isMainPage() {
1259 return $this->equals( self
::newMainPage() );
1263 * Is this a subpage?
1267 public function isSubpage() {
1268 return MWNamespace
::hasSubpages( $this->mNamespace
)
1269 ?
strpos( $this->getText(), '/' ) !== false
1274 * Is this a conversion table for the LanguageConverter?
1278 public function isConversionTable() {
1279 // @todo ConversionTable should become a separate content model.
1281 return $this->mNamespace
== NS_MEDIAWIKI
&&
1282 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1286 * Does that page contain wikitext, or it is JS, CSS or whatever?
1290 public function isWikitextPage() {
1291 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1295 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1296 * global UI. This is generally true for pages in the MediaWiki namespace having
1297 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1299 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1302 * Note that this method should not return true for pages that contain and show
1303 * "inactive" CSS, JSON, or JS.
1308 public function isSiteConfigPage() {
1310 $this->isSiteCssConfigPage()
1311 ||
$this->isSiteJsonConfigPage()
1312 ||
$this->isSiteJsConfigPage()
1317 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1322 public function isUserConfigPage() {
1324 $this->isUserCssConfigPage()
1325 ||
$this->isUserJsonConfigPage()
1326 ||
$this->isUserJsConfigPage()
1331 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1333 * @return string Containing skin name from .css, .json, or .js subpage title
1336 public function getSkinFromConfigSubpage() {
1337 $subpage = explode( '/', $this->mTextform
);
1338 $subpage = $subpage[count( $subpage ) - 1];
1339 $lastdot = strrpos( $subpage, '.' );
1340 if ( $lastdot === false ) {
1341 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1343 return substr( $subpage, 0, $lastdot );
1347 * Is this a CSS "config" sub-page of a user page?
1352 public function isUserCssConfigPage() {
1354 NS_USER
== $this->mNamespace
1355 && $this->isSubpage()
1356 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1361 * Is this a JSON "config" sub-page of a user page?
1366 public function isUserJsonConfigPage() {
1368 NS_USER
== $this->mNamespace
1369 && $this->isSubpage()
1370 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1375 * Is this a JS "config" sub-page of a user page?
1380 public function isUserJsConfigPage() {
1382 NS_USER
== $this->mNamespace
1383 && $this->isSubpage()
1384 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1389 * Is this a sitewide CSS "config" page?
1394 public function isSiteCssConfigPage() {
1396 NS_MEDIAWIKI
== $this->mNamespace
1398 $this->hasContentModel( CONTENT_MODEL_CSS
)
1399 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1400 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1401 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1407 * Is this a sitewide JSON "config" page?
1412 public function isSiteJsonConfigPage() {
1414 NS_MEDIAWIKI
== $this->mNamespace
1416 $this->hasContentModel( CONTENT_MODEL_JSON
)
1417 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1418 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1419 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1425 * Is this a sitewide JS "config" page?
1430 public function isSiteJsConfigPage() {
1432 NS_MEDIAWIKI
== $this->mNamespace
1434 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1435 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1436 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1437 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1443 * Is this a message which can contain raw HTML?
1448 public function isRawHtmlMessage() {
1449 global $wgRawHtmlMessages;
1451 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1454 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1455 return in_array( $message, $wgRawHtmlMessages, true );
1459 * Is this a talk page of some sort?
1463 public function isTalkPage() {
1464 return MWNamespace
::isTalk( $this->mNamespace
);
1468 * Get a Title object associated with the talk page of this article
1470 * @return Title The object for the talk page
1472 public function getTalkPage() {
1473 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1477 * Get a Title object associated with the talk page of this article,
1478 * if such a talk page can exist.
1482 * @return Title|null The object for the talk page,
1483 * or null if no associated talk page can exist, according to canHaveTalkPage().
1485 public function getTalkPageIfDefined() {
1486 if ( !$this->canHaveTalkPage() ) {
1490 return $this->getTalkPage();
1494 * Get a title object associated with the subject page of this
1497 * @return Title The object for the subject page
1499 public function getSubjectPage() {
1500 // Is this the same title?
1501 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1502 if ( $this->mNamespace
== $subjectNS ) {
1505 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1509 * Get the other title for this page, if this is a subject page
1510 * get the talk page, if it is a subject page get the talk page
1513 * @throws MWException If the page doesn't have an other page
1516 public function getOtherPage() {
1517 if ( $this->isSpecialPage() ) {
1518 throw new MWException( 'Special pages cannot have other pages' );
1520 if ( $this->isTalkPage() ) {
1521 return $this->getSubjectPage();
1523 if ( !$this->canHaveTalkPage() ) {
1524 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1526 return $this->getTalkPage();
1531 * Get the default namespace index, for when there is no namespace
1533 * @return int Default namespace index
1535 public function getDefaultNamespace() {
1536 return $this->mDefaultNamespace
;
1540 * Get the Title fragment (i.e.\ the bit after the #) in text form
1542 * Use Title::hasFragment to check for a fragment
1544 * @return string Title fragment
1546 public function getFragment() {
1547 return $this->mFragment
;
1551 * Check if a Title fragment is set
1556 public function hasFragment() {
1557 return $this->mFragment
!== '';
1561 * Get the fragment in URL form, including the "#" character if there is one
1563 * @return string Fragment in URL form
1565 public function getFragmentForURL() {
1566 if ( !$this->hasFragment() ) {
1568 } elseif ( $this->isExternal() ) {
1569 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1570 // so we treat it like a local interwiki.
1571 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1572 if ( $interwiki && !$interwiki->isLocal() ) {
1573 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1577 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1581 * Set the fragment for this title. Removes the first character from the
1582 * specified fragment before setting, so it assumes you're passing it with
1585 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1586 * or Title::createFragmentTarget().
1587 * Still in active use privately.
1590 * @param string $fragment Text
1592 public function setFragment( $fragment ) {
1593 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1597 * Creates a new Title for a different fragment of the same page.
1600 * @param string $fragment
1603 public function createFragmentTarget( $fragment ) {
1604 return self
::makeTitle(
1613 * Prefix some arbitrary text with the namespace or interwiki prefix
1616 * @param string $name The text
1617 * @return string The prefixed text
1619 private function prefix( $name ) {
1621 if ( $this->isExternal() ) {
1622 $p = $this->mInterwiki
. ':';
1625 if ( $this->mNamespace
!= 0 ) {
1626 $nsText = $this->getNsText();
1628 if ( $nsText === false ) {
1629 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1630 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1631 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1634 $p .= $nsText . ':';
1640 * Get the prefixed database key form
1642 * @return string The prefixed title, with underscores and
1643 * any interwiki and namespace prefixes
1645 public function getPrefixedDBkey() {
1646 $s = $this->prefix( $this->mDbkeyform
);
1647 $s = strtr( $s, ' ', '_' );
1652 * Get the prefixed title with spaces.
1653 * This is the form usually used for display
1655 * @return string The prefixed title, with spaces
1657 public function getPrefixedText() {
1658 if ( $this->prefixedText
=== null ) {
1659 $s = $this->prefix( $this->mTextform
);
1660 $s = strtr( $s, '_', ' ' );
1661 $this->prefixedText
= $s;
1663 return $this->prefixedText
;
1667 * Return a string representation of this title
1669 * @return string Representation of this title
1671 public function __toString() {
1672 return $this->getPrefixedText();
1676 * Get the prefixed title with spaces, plus any fragment
1677 * (part beginning with '#')
1679 * @return string The prefixed title, with spaces and the fragment, including '#'
1681 public function getFullText() {
1682 $text = $this->getPrefixedText();
1683 if ( $this->hasFragment() ) {
1684 $text .= '#' . $this->mFragment
;
1690 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1694 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1698 * @return string Root name
1701 public function getRootText() {
1702 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1703 return $this->getText();
1706 return strtok( $this->getText(), '/' );
1710 * Get the root page name title, i.e. the leftmost part before any slashes
1714 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1715 * # returns: Title{User:Foo}
1718 * @return Title Root title
1721 public function getRootTitle() {
1722 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1726 * Get the base page name without a namespace, i.e. the part before the subpage name
1730 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1731 * # returns: 'Foo/Bar'
1734 * @return string Base name
1736 public function getBaseText() {
1737 $text = $this->getText();
1738 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1742 $lastSlashPos = strrpos( $text, '/' );
1743 // Don't discard the real title if there's no subpage involved
1744 if ( $lastSlashPos === false ) {
1748 return substr( $text, 0, $lastSlashPos );
1752 * Get the base page name title, i.e. the part before the subpage name
1756 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1757 * # returns: Title{User:Foo/Bar}
1760 * @return Title Base title
1763 public function getBaseTitle() {
1764 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1768 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1772 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1776 * @return string Subpage name
1778 public function getSubpageText() {
1779 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1780 return $this->mTextform
;
1782 $parts = explode( '/', $this->mTextform
);
1783 return $parts[count( $parts ) - 1];
1787 * Get the title for a subpage of the current page
1791 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1792 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1795 * @param string $text The subpage name to add to the title
1796 * @return Title|null Subpage title, or null on an error
1799 public function getSubpage( $text ) {
1800 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1804 * Get a URL-encoded form of the subpage text
1806 * @return string URL-encoded subpage name
1808 public function getSubpageUrlForm() {
1809 $text = $this->getSubpageText();
1810 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1815 * Get a URL-encoded title (not an actual URL) including interwiki
1817 * @return string The URL-encoded form
1819 public function getPrefixedURL() {
1820 $s = $this->prefix( $this->mDbkeyform
);
1821 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1826 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1827 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1828 * second argument named variant. This was deprecated in favor
1829 * of passing an array of option with a "variant" key
1830 * Once $query2 is removed for good, this helper can be dropped
1831 * and the wfArrayToCgi moved to getLocalURL();
1833 * @since 1.19 (r105919)
1834 * @param array|string $query
1835 * @param string|string[]|bool $query2
1838 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1839 if ( $query2 !== false ) {
1840 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1841 "method called with a second parameter is deprecated. Add your " .
1842 "parameter to an array passed as the first parameter.", "1.19" );
1844 if ( is_array( $query ) ) {
1845 $query = wfArrayToCgi( $query );
1848 if ( is_string( $query2 ) ) {
1849 // $query2 is a string, we will consider this to be
1850 // a deprecated $variant argument and add it to the query
1851 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1853 $query2 = wfArrayToCgi( $query2 );
1855 // If we have $query content add a & to it first
1859 // Now append the queries together
1866 * Get a real URL referring to this title, with interwiki link and
1869 * @see self::getLocalURL for the arguments.
1871 * @param string|string[] $query
1872 * @param string|string[]|bool $query2
1873 * @param string|int|null $proto Protocol type to use in URL
1874 * @return string The URL
1876 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1877 $query = self
::fixUrlQueryArgs( $query, $query2 );
1879 # Hand off all the decisions on urls to getLocalURL
1880 $url = $this->getLocalURL( $query );
1882 # Expand the url to make it a full url. Note that getLocalURL has the
1883 # potential to output full urls for a variety of reasons, so we use
1884 # wfExpandUrl instead of simply prepending $wgServer
1885 $url = wfExpandUrl( $url, $proto );
1887 # Finally, add the fragment.
1888 $url .= $this->getFragmentForURL();
1889 // Avoid PHP 7.1 warning from passing $this by reference
1891 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1896 * Get a url appropriate for making redirects based on an untrusted url arg
1898 * This is basically the same as getFullUrl(), but in the case of external
1899 * interwikis, we send the user to a landing page, to prevent possible
1900 * phishing attacks and the like.
1902 * @note Uses current protocol by default, since technically relative urls
1903 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1904 * places where the url gets cached, as might pollute between
1905 * https and non-https users.
1906 * @see self::getLocalURL for the arguments.
1907 * @param array|string $query
1908 * @param string $proto Protocol type to use in URL
1909 * @return string A url suitable to use in an HTTP location header.
1911 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1913 if ( $this->isExternal() ) {
1914 $target = SpecialPage
::getTitleFor(
1916 $this->getPrefixedDBkey()
1919 return $target->getFullURL( $query, false, $proto );
1923 * Get a URL with no fragment or server name (relative URL) from a Title object.
1924 * If this page is generated with action=render, however,
1925 * $wgServer is prepended to make an absolute URL.
1927 * @see self::getFullURL to always get an absolute URL.
1928 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1929 * valid to link, locally, to the current Title.
1930 * @see self::newFromText to produce a Title object.
1932 * @param string|string[] $query An optional query string,
1933 * not used for interwiki links. Can be specified as an associative array as well,
1934 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1935 * Some query patterns will trigger various shorturl path replacements.
1936 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1937 * be an array. If a string is passed it will be interpreted as a deprecated
1938 * variant argument and urlencoded into a variant= argument.
1939 * This second query argument will be added to the $query
1940 * The second parameter is deprecated since 1.19. Pass it as a key,value
1941 * pair in the first parameter array instead.
1943 * @return string String of the URL.
1945 public function getLocalURL( $query = '', $query2 = false ) {
1946 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1948 $query = self
::fixUrlQueryArgs( $query, $query2 );
1950 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1952 $namespace = $this->getNsText();
1953 if ( $namespace != '' ) {
1954 # Can this actually happen? Interwikis shouldn't be parsed.
1955 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1958 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1959 $url = wfAppendQuery( $url, $query );
1961 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1962 if ( $query == '' ) {
1963 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1964 // Avoid PHP 7.1 warning from passing $this by reference
1966 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1968 global $wgVariantArticlePath, $wgActionPaths;
1972 if ( !empty( $wgActionPaths )
1973 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1975 $action = urldecode( $matches[2] );
1976 if ( isset( $wgActionPaths[$action] ) ) {
1977 $query = $matches[1];
1978 if ( isset( $matches[4] ) ) {
1979 $query .= $matches[4];
1981 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1982 if ( $query != '' ) {
1983 $url = wfAppendQuery( $url, $query );
1989 && $wgVariantArticlePath
1990 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1991 && $this->getPageLanguage()->equals(
1992 MediaWikiServices
::getInstance()->getContentLanguage() )
1993 && $this->getPageLanguage()->hasVariants()
1995 $variant = urldecode( $matches[1] );
1996 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1997 // Only do the variant replacement if the given variant is a valid
1998 // variant for the page's language.
1999 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2000 $url = str_replace( '$1', $dbkey, $url );
2004 if ( $url === false ) {
2005 if ( $query == '-' ) {
2008 $url = "{$wgScript}?title={$dbkey}&{$query}";
2011 // Avoid PHP 7.1 warning from passing $this by reference
2013 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2015 // @todo FIXME: This causes breakage in various places when we
2016 // actually expected a local URL and end up with dupe prefixes.
2017 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2018 $url = $wgServer . $url;
2021 // Avoid PHP 7.1 warning from passing $this by reference
2023 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2028 * Get a URL that's the simplest URL that will be valid to link, locally,
2029 * to the current Title. It includes the fragment, but does not include
2030 * the server unless action=render is used (or the link is external). If
2031 * there's a fragment but the prefixed text is empty, we just return a link
2034 * The result obviously should not be URL-escaped, but does need to be
2035 * HTML-escaped if it's being output in HTML.
2037 * @param string|string[] $query
2038 * @param bool $query2
2039 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2040 * or false (default) for no expansion
2041 * @see self::getLocalURL for the arguments.
2042 * @return string The URL
2044 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2045 if ( $this->isExternal() ||
$proto !== false ) {
2046 $ret = $this->getFullURL( $query, $query2, $proto );
2047 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2048 $ret = $this->getFragmentForURL();
2050 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2056 * Get the URL form for an internal link.
2057 * - Used in various CDN-related code, in case we have a different
2058 * internal hostname for the server from the exposed one.
2060 * This uses $wgInternalServer to qualify the path, or $wgServer
2061 * if $wgInternalServer is not set. If the server variable used is
2062 * protocol-relative, the URL will be expanded to http://
2064 * @see self::getLocalURL for the arguments.
2065 * @param string $query
2066 * @param string|bool $query2
2067 * @return string The URL
2069 public function getInternalURL( $query = '', $query2 = false ) {
2070 global $wgInternalServer, $wgServer;
2071 $query = self
::fixUrlQueryArgs( $query, $query2 );
2072 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2073 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2074 // Avoid PHP 7.1 warning from passing $this by reference
2076 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2081 * Get the URL for a canonical link, for use in things like IRC and
2082 * e-mail notifications. Uses $wgCanonicalServer and the
2083 * GetCanonicalURL hook.
2085 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2087 * @see self::getLocalURL for the arguments.
2088 * @param string $query
2089 * @param string|bool $query2
2090 * @return string The URL
2093 public function getCanonicalURL( $query = '', $query2 = false ) {
2094 $query = self
::fixUrlQueryArgs( $query, $query2 );
2095 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2096 // Avoid PHP 7.1 warning from passing $this by reference
2098 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2103 * Get the edit URL for this Title
2105 * @return string The URL, or a null string if this is an interwiki link
2107 public function getEditURL() {
2108 if ( $this->isExternal() ) {
2111 $s = $this->getLocalURL( 'action=edit' );
2117 * Can $user perform $action on this page?
2118 * This skips potentially expensive cascading permission checks
2119 * as well as avoids expensive error formatting
2121 * Suitable for use for nonessential UI controls in common cases, but
2122 * _not_ for functional access control.
2124 * May provide false positives, but should never provide a false negative.
2126 * @param string $action Action that permission needs to be checked for
2127 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2132 * @deprecated since 1.33,
2133 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2136 public function quickUserCan( $action, $user = null ) {
2137 return $this->userCan( $action, $user, false );
2141 * Can $user perform $action on this page?
2143 * @param string $action Action that permission needs to be checked for
2144 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2146 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2151 * @deprecated since 1.33,
2152 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2155 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2156 if ( !$user instanceof User
) {
2161 // TODO: this is for b/c, eventually will be removed
2162 if ( $rigor === true ) {
2163 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2164 } elseif ( $rigor === false ) {
2165 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2168 return MediaWikiServices
::getInstance()->getPermissionManager()
2169 ->userCan( $action, $user, $this, $rigor );
2173 * Can $user perform $action on this page?
2175 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2177 * @param string $action Action that permission needs to be checked for
2178 * @param User $user User to check
2179 * @param string $rigor One of (quick,full,secure)
2180 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2181 * - full : does cheap and expensive checks possibly from a replica DB
2182 * - secure : does cheap and expensive checks, using the master as needed
2183 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2184 * whose corresponding errors may be ignored.
2186 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2189 * @deprecated since 1.33,
2190 * use MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissionsErrors()
2193 public function getUserPermissionsErrors(
2194 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2196 // TODO: this is for b/c, eventually will be removed
2197 if ( $rigor === true ) {
2198 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2199 } elseif ( $rigor === false ) {
2200 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2203 return MediaWikiServices
::getInstance()->getPermissionManager()
2204 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2208 * Add the resulting error code to the errors array
2210 * @param array $errors List of current errors
2211 * @param array $result Result of errors
2213 * @return array List of errors
2215 private function resultToError( $errors, $result ) {
2216 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2217 // A single array representing an error
2218 $errors[] = $result;
2219 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2220 // A nested array representing multiple errors
2221 $errors = array_merge( $errors, $result );
2222 } elseif ( $result !== '' && is_string( $result ) ) {
2223 // A string representing a message-id
2224 $errors[] = [ $result ];
2225 } elseif ( $result instanceof MessageSpecifier
) {
2226 // A message specifier representing an error
2227 $errors[] = [ $result ];
2228 } elseif ( $result === false ) {
2229 // a generic "We don't want them to do that"
2230 $errors[] = [ 'badaccess-group0' ];
2236 * Get a filtered list of all restriction types supported by this wiki.
2237 * @param bool $exists True to get all restriction types that apply to
2238 * titles that do exist, False for all restriction types that apply to
2239 * titles that do not exist
2242 public static function getFilteredRestrictionTypes( $exists = true ) {
2243 global $wgRestrictionTypes;
2244 $types = $wgRestrictionTypes;
2246 # Remove the create restriction for existing titles
2247 $types = array_diff( $types, [ 'create' ] );
2249 # Only the create and upload restrictions apply to non-existing titles
2250 $types = array_intersect( $types, [ 'create', 'upload' ] );
2256 * Returns restriction types for the current Title
2258 * @return array Applicable restriction types
2260 public function getRestrictionTypes() {
2261 if ( $this->isSpecialPage() ) {
2265 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2267 if ( $this->mNamespace
!= NS_FILE
) {
2268 # Remove the upload restriction for non-file titles
2269 $types = array_diff( $types, [ 'upload' ] );
2272 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2274 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2275 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2281 * Is this title subject to title protection?
2282 * Title protection is the one applied against creation of such title.
2284 * @return array|bool An associative array representing any existent title
2285 * protection, or false if there's none.
2287 public function getTitleProtection() {
2288 $protection = $this->getTitleProtectionInternal();
2289 if ( $protection ) {
2290 if ( $protection['permission'] == 'sysop' ) {
2291 $protection['permission'] = 'editprotected'; // B/C
2293 if ( $protection['permission'] == 'autoconfirmed' ) {
2294 $protection['permission'] = 'editsemiprotected'; // B/C
2301 * Fetch title protection settings
2303 * To work correctly, $this->loadRestrictions() needs to have access to the
2304 * actual protections in the database without munging 'sysop' =>
2305 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2306 * callers probably want $this->getTitleProtection() instead.
2308 * @return array|bool
2310 protected function getTitleProtectionInternal() {
2311 // Can't protect pages in special namespaces
2312 if ( $this->mNamespace
< 0 ) {
2316 // Can't protect pages that exist.
2317 if ( $this->exists() ) {
2321 if ( $this->mTitleProtection
=== null ) {
2322 $dbr = wfGetDB( DB_REPLICA
);
2323 $commentStore = CommentStore
::getStore();
2324 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2325 $res = $dbr->select(
2326 [ 'protected_titles' ] +
$commentQuery['tables'],
2328 'user' => 'pt_user',
2329 'expiry' => 'pt_expiry',
2330 'permission' => 'pt_create_perm'
2331 ] +
$commentQuery['fields'],
2332 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2335 $commentQuery['joins']
2338 // fetchRow returns false if there are no rows.
2339 $row = $dbr->fetchRow( $res );
2341 $this->mTitleProtection
= [
2342 'user' => $row['user'],
2343 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2344 'permission' => $row['permission'],
2345 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2348 $this->mTitleProtection
= false;
2351 return $this->mTitleProtection
;
2355 * Remove any title protection due to page existing
2357 public function deleteTitleProtection() {
2358 $dbw = wfGetDB( DB_MASTER
);
2362 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2365 $this->mTitleProtection
= false;
2369 * Is this page "semi-protected" - the *only* protection levels are listed
2370 * in $wgSemiprotectedRestrictionLevels?
2372 * @param string $action Action to check (default: edit)
2375 public function isSemiProtected( $action = 'edit' ) {
2376 global $wgSemiprotectedRestrictionLevels;
2378 $restrictions = $this->getRestrictions( $action );
2379 $semi = $wgSemiprotectedRestrictionLevels;
2380 if ( !$restrictions ||
!$semi ) {
2381 // Not protected, or all protection is full protection
2385 // Remap autoconfirmed to editsemiprotected for BC
2386 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2387 $semi[$key] = 'editsemiprotected';
2389 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2390 $restrictions[$key] = 'editsemiprotected';
2393 return !array_diff( $restrictions, $semi );
2397 * Does the title correspond to a protected article?
2399 * @param string $action The action the page is protected from,
2400 * by default checks all actions.
2403 public function isProtected( $action = '' ) {
2404 global $wgRestrictionLevels;
2406 $restrictionTypes = $this->getRestrictionTypes();
2408 # Special pages have inherent protection
2409 if ( $this->isSpecialPage() ) {
2413 # Check regular protection levels
2414 foreach ( $restrictionTypes as $type ) {
2415 if ( $action == $type ||
$action == '' ) {
2416 $r = $this->getRestrictions( $type );
2417 foreach ( $wgRestrictionLevels as $level ) {
2418 if ( in_array( $level, $r ) && $level != '' ) {
2429 * Determines if $user is unable to edit this page because it has been protected
2430 * by $wgNamespaceProtection.
2432 * @param User $user User object to check permissions
2435 public function isNamespaceProtected( User
$user ) {
2436 global $wgNamespaceProtection;
2438 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2439 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2440 if ( $right != '' && !$user->isAllowed( $right ) ) {
2449 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2451 * @return bool If the page is subject to cascading restrictions.
2453 public function isCascadeProtected() {
2454 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2455 return ( $sources > 0 );
2459 * Determines whether cascading protection sources have already been loaded from
2462 * @param bool $getPages True to check if the pages are loaded, or false to check
2463 * if the status is loaded.
2464 * @return bool Whether or not the specified information has been loaded
2467 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2468 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2472 * Cascading protection: Get the source of any cascading restrictions on this page.
2474 * @param bool $getPages Whether or not to retrieve the actual pages
2475 * that the restrictions have come from and the actual restrictions
2477 * @return array Two elements: First is an array of Title objects of the
2478 * pages from which cascading restrictions have come, false for
2479 * none, or true if such restrictions exist but $getPages was not
2480 * set. Second is an array like that returned by
2481 * Title::getAllRestrictions(), or an empty array if $getPages is
2484 public function getCascadeProtectionSources( $getPages = true ) {
2485 $pagerestrictions = [];
2487 if ( $this->mCascadeSources
!== null && $getPages ) {
2488 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2489 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2490 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2493 $dbr = wfGetDB( DB_REPLICA
);
2495 if ( $this->mNamespace
== NS_FILE
) {
2496 $tables = [ 'imagelinks', 'page_restrictions' ];
2498 'il_to' => $this->mDbkeyform
,
2503 $tables = [ 'templatelinks', 'page_restrictions' ];
2505 'tl_namespace' => $this->mNamespace
,
2506 'tl_title' => $this->mDbkeyform
,
2513 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2514 'pr_expiry', 'pr_type', 'pr_level' ];
2515 $where_clauses[] = 'page_id=pr_page';
2518 $cols = [ 'pr_expiry' ];
2521 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2523 $sources = $getPages ?
[] : false;
2524 $now = wfTimestampNow();
2526 foreach ( $res as $row ) {
2527 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2528 if ( $expiry > $now ) {
2530 $page_id = $row->pr_page
;
2531 $page_ns = $row->page_namespace
;
2532 $page_title = $row->page_title
;
2533 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2534 # Add groups needed for each restriction type if its not already there
2535 # Make sure this restriction type still exists
2537 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2538 $pagerestrictions[$row->pr_type
] = [];
2542 isset( $pagerestrictions[$row->pr_type
] )
2543 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2545 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2554 $this->mCascadeSources
= $sources;
2555 $this->mCascadingRestrictions
= $pagerestrictions;
2557 $this->mHasCascadingRestrictions
= $sources;
2560 return [ $sources, $pagerestrictions ];
2564 * Accessor for mRestrictionsLoaded
2566 * @return bool Whether or not the page's restrictions have already been
2567 * loaded from the database
2570 public function areRestrictionsLoaded() {
2571 return $this->mRestrictionsLoaded
;
2575 * Accessor/initialisation for mRestrictions
2577 * @param string $action Action that permission needs to be checked for
2578 * @return array Restriction levels needed to take the action. All levels are
2579 * required. Note that restriction levels are normally user rights, but 'sysop'
2580 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2581 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2583 public function getRestrictions( $action ) {
2584 if ( !$this->mRestrictionsLoaded
) {
2585 $this->loadRestrictions();
2587 return $this->mRestrictions
[$action] ??
[];
2591 * Accessor/initialisation for mRestrictions
2593 * @return array Keys are actions, values are arrays as returned by
2594 * Title::getRestrictions()
2597 public function getAllRestrictions() {
2598 if ( !$this->mRestrictionsLoaded
) {
2599 $this->loadRestrictions();
2601 return $this->mRestrictions
;
2605 * Get the expiry time for the restriction against a given action
2607 * @param string $action
2608 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2609 * or not protected at all, or false if the action is not recognised.
2611 public function getRestrictionExpiry( $action ) {
2612 if ( !$this->mRestrictionsLoaded
) {
2613 $this->loadRestrictions();
2615 return $this->mRestrictionsExpiry
[$action] ??
false;
2619 * Returns cascading restrictions for the current article
2623 function areRestrictionsCascading() {
2624 if ( !$this->mRestrictionsLoaded
) {
2625 $this->loadRestrictions();
2628 return $this->mCascadeRestriction
;
2632 * Compiles list of active page restrictions from both page table (pre 1.10)
2633 * and page_restrictions table for this existing page.
2634 * Public for usage by LiquidThreads.
2636 * @param array $rows Array of db result objects
2637 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2638 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2639 * Edit and move sections are separated by a colon
2640 * Example: "edit=autoconfirmed,sysop:move=sysop"
2642 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2643 // This function will only read rows from a table that we migrated away
2644 // from before adding READ_LATEST support to loadRestrictions, so we
2645 // don't need to support reading from DB_MASTER here.
2646 $dbr = wfGetDB( DB_REPLICA
);
2648 $restrictionTypes = $this->getRestrictionTypes();
2650 foreach ( $restrictionTypes as $type ) {
2651 $this->mRestrictions
[$type] = [];
2652 $this->mRestrictionsExpiry
[$type] = 'infinity';
2655 $this->mCascadeRestriction
= false;
2657 # Backwards-compatibility: also load the restrictions from the page record (old format).
2658 if ( $oldFashionedRestrictions !== null ) {
2659 $this->mOldRestrictions
= $oldFashionedRestrictions;
2662 if ( $this->mOldRestrictions
=== false ) {
2663 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2664 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2665 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2668 if ( $this->mOldRestrictions
!= '' ) {
2669 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2670 $temp = explode( '=', trim( $restrict ) );
2671 if ( count( $temp ) == 1 ) {
2672 // old old format should be treated as edit/move restriction
2673 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2674 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2676 $restriction = trim( $temp[1] );
2677 if ( $restriction != '' ) { // some old entries are empty
2678 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2684 if ( count( $rows ) ) {
2685 # Current system - load second to make them override.
2686 $now = wfTimestampNow();
2688 # Cycle through all the restrictions.
2689 foreach ( $rows as $row ) {
2690 // Don't take care of restrictions types that aren't allowed
2691 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2695 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2697 // Only apply the restrictions if they haven't expired!
2698 if ( !$expiry ||
$expiry > $now ) {
2699 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2700 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2702 $this->mCascadeRestriction |
= $row->pr_cascade
;
2707 $this->mRestrictionsLoaded
= true;
2711 * Load restrictions from the page_restrictions table
2713 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2714 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2715 * Edit and move sections are separated by a colon
2716 * Example: "edit=autoconfirmed,sysop:move=sysop"
2717 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2718 * from the master DB.
2720 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2721 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2722 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2726 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2727 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2728 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2729 $id = $this->getArticleID();
2731 $fname = __METHOD__
;
2732 $loadRestrictionsFromDb = function ( Database
$dbr ) use ( $fname, $id ) {
2733 return iterator_to_array(
2735 'page_restrictions',
2736 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2737 [ 'pr_page' => $id ],
2743 if ( $readLatest ) {
2744 $dbr = wfGetDB( DB_MASTER
);
2745 $rows = $loadRestrictionsFromDb( $dbr );
2747 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2748 $rows = $cache->getWithSetCallback(
2749 // Page protections always leave a new null revision
2750 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2752 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2753 $dbr = wfGetDB( DB_REPLICA
);
2755 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2756 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2757 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2758 // @TODO: cleanup Title cache and caller assumption mess in general
2759 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2762 return $loadRestrictionsFromDb( $dbr );
2767 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2769 $title_protection = $this->getTitleProtectionInternal();
2771 if ( $title_protection ) {
2772 $now = wfTimestampNow();
2773 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2775 if ( !$expiry ||
$expiry > $now ) {
2776 // Apply the restrictions
2777 $this->mRestrictionsExpiry
['create'] = $expiry;
2778 $this->mRestrictions
['create'] =
2779 explode( ',', trim( $title_protection['permission'] ) );
2780 } else { // Get rid of the old restrictions
2781 $this->mTitleProtection
= false;
2784 $this->mRestrictionsExpiry
['create'] = 'infinity';
2786 $this->mRestrictionsLoaded
= true;
2791 * Flush the protection cache in this object and force reload from the database.
2792 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2794 public function flushRestrictions() {
2795 $this->mRestrictionsLoaded
= false;
2796 $this->mTitleProtection
= null;
2800 * Purge expired restrictions from the page_restrictions table
2802 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2804 static function purgeExpiredRestrictions() {
2805 if ( wfReadOnly() ) {
2809 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2810 wfGetDB( DB_MASTER
),
2812 function ( IDatabase
$dbw, $fname ) {
2813 $config = MediaWikiServices
::getInstance()->getMainConfig();
2814 $ids = $dbw->selectFieldValues(
2815 'page_restrictions',
2817 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2819 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2822 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2827 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2828 wfGetDB( DB_MASTER
),
2830 function ( IDatabase
$dbw, $fname ) {
2833 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2841 * Does this have subpages? (Warning, usually requires an extra DB query.)
2845 public function hasSubpages() {
2846 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2851 # We dynamically add a member variable for the purpose of this method
2852 # alone to cache the result. There's no point in having it hanging
2853 # around uninitialized in every Title object; therefore we only add it
2854 # if needed and don't declare it statically.
2855 if ( $this->mHasSubpages
=== null ) {
2856 $this->mHasSubpages
= false;
2857 $subpages = $this->getSubpages( 1 );
2858 if ( $subpages instanceof TitleArray
) {
2859 $this->mHasSubpages
= (bool)$subpages->count();
2863 return $this->mHasSubpages
;
2867 * Get all subpages of this page.
2869 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2870 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2871 * doesn't allow subpages
2873 public function getSubpages( $limit = -1 ) {
2874 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2878 $dbr = wfGetDB( DB_REPLICA
);
2879 $conds['page_namespace'] = $this->mNamespace
;
2880 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2882 if ( $limit > -1 ) {
2883 $options['LIMIT'] = $limit;
2885 return TitleArray
::newFromResult(
2886 $dbr->select( 'page',
2887 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2896 * Is there a version of this page in the deletion archive?
2898 * @return int The number of archived revisions
2900 public function isDeleted() {
2901 if ( $this->mNamespace
< 0 ) {
2904 $dbr = wfGetDB( DB_REPLICA
);
2906 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2907 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2910 if ( $this->mNamespace
== NS_FILE
) {
2911 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2912 [ 'fa_name' => $this->mDbkeyform
],
2921 * Is there a version of this page in the deletion archive?
2925 public function isDeletedQuick() {
2926 if ( $this->mNamespace
< 0 ) {
2929 $dbr = wfGetDB( DB_REPLICA
);
2930 $deleted = (bool)$dbr->selectField( 'archive', '1',
2931 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2934 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
2935 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2936 [ 'fa_name' => $this->mDbkeyform
],
2944 * Get the article ID for this Title from the link cache,
2945 * adding it if necessary
2947 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
2949 * @return int The ID
2951 public function getArticleID( $flags = 0 ) {
2952 if ( $this->mNamespace
< 0 ) {
2953 $this->mArticleID
= 0;
2954 return $this->mArticleID
;
2956 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2957 if ( $flags & self
::GAID_FOR_UPDATE
) {
2958 $oldUpdate = $linkCache->forUpdate( true );
2959 $linkCache->clearLink( $this );
2960 $this->mArticleID
= $linkCache->addLinkObj( $this );
2961 $linkCache->forUpdate( $oldUpdate );
2963 if ( $this->mArticleID
== -1 ) {
2964 $this->mArticleID
= $linkCache->addLinkObj( $this );
2967 return $this->mArticleID
;
2971 * Is this an article that is a redirect page?
2972 * Uses link cache, adding it if necessary
2974 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
2977 public function isRedirect( $flags = 0 ) {
2978 if ( !is_null( $this->mRedirect
) ) {
2979 return $this->mRedirect
;
2981 if ( !$this->getArticleID( $flags ) ) {
2982 $this->mRedirect
= false;
2983 return $this->mRedirect
;
2986 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2987 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2988 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2989 if ( $cached === null ) {
2990 # Trust LinkCache's state over our own
2991 # LinkCache is telling us that the page doesn't exist, despite there being cached
2992 # data relating to an existing page in $this->mArticleID. Updaters should clear
2993 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
2994 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
2995 # LinkCache to refresh its data from the master.
2996 $this->mRedirect
= false;
2997 return $this->mRedirect
;
3000 $this->mRedirect
= (bool)$cached;
3002 return $this->mRedirect
;
3006 * What is the length of this page?
3007 * Uses link cache, adding it if necessary
3009 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3012 public function getLength( $flags = 0 ) {
3013 if ( $this->mLength
!= -1 ) {
3014 return $this->mLength
;
3016 if ( !$this->getArticleID( $flags ) ) {
3018 return $this->mLength
;
3020 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3021 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3022 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3023 if ( $cached === null ) {
3024 # Trust LinkCache's state over our own, as for isRedirect()
3026 return $this->mLength
;
3029 $this->mLength
= intval( $cached );
3031 return $this->mLength
;
3035 * What is the page_latest field for this page?
3037 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3038 * @return int Int or 0 if the page doesn't exist
3040 public function getLatestRevID( $flags = 0 ) {
3041 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3042 return intval( $this->mLatestID
);
3044 if ( !$this->getArticleID( $flags ) ) {
3045 $this->mLatestID
= 0;
3046 return $this->mLatestID
;
3048 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3049 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3050 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3051 if ( $cached === null ) {
3052 # Trust LinkCache's state over our own, as for isRedirect()
3053 $this->mLatestID
= 0;
3054 return $this->mLatestID
;
3057 $this->mLatestID
= intval( $cached );
3059 return $this->mLatestID
;
3063 * This clears some fields in this object, and clears any associated
3064 * keys in the "bad links" section of the link cache.
3066 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3067 * loading of the new page_id. It's also called from
3068 * WikiPage::doDeleteArticleReal()
3070 * @param int $newid The new Article ID
3072 public function resetArticleID( $newid ) {
3073 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3074 $linkCache->clearLink( $this );
3076 if ( $newid === false ) {
3077 $this->mArticleID
= -1;
3079 $this->mArticleID
= intval( $newid );
3081 $this->mRestrictionsLoaded
= false;
3082 $this->mRestrictions
= [];
3083 $this->mOldRestrictions
= false;
3084 $this->mRedirect
= null;
3085 $this->mLength
= -1;
3086 $this->mLatestID
= false;
3087 $this->mContentModel
= false;
3088 $this->mEstimateRevisions
= null;
3089 $this->mPageLanguage
= false;
3090 $this->mDbPageLanguage
= false;
3091 $this->mIsBigDeletion
= null;
3094 public static function clearCaches() {
3095 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3096 $linkCache->clear();
3098 $titleCache = self
::getTitleCache();
3099 $titleCache->clear();
3103 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3105 * @param string $text Containing title to capitalize
3106 * @param int $ns Namespace index, defaults to NS_MAIN
3107 * @return string Containing capitalized title
3109 public static function capitalize( $text, $ns = NS_MAIN
) {
3110 if ( MWNamespace
::isCapitalized( $ns ) ) {
3111 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3118 * Secure and split - main initialisation function for this object
3120 * Assumes that mDbkeyform has been set, and is urldecoded
3121 * and uses underscores, but not otherwise munged. This function
3122 * removes illegal characters, splits off the interwiki and
3123 * namespace prefixes, sets the other forms, and canonicalizes
3126 * @throws MalformedTitleException On invalid titles
3127 * @return bool True on success
3129 private function secureAndSplit() {
3130 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3131 // the parsing code with Title, while avoiding massive refactoring.
3132 // @todo: get rid of secureAndSplit, refactor parsing code.
3133 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3134 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3135 /** @var MediaWikiTitleCodec $titleCodec */
3136 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3137 // MalformedTitleException can be thrown here
3138 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3141 $this->setFragment( '#' . $parts['fragment'] );
3142 $this->mInterwiki
= $parts['interwiki'];
3143 $this->mLocalInterwiki
= $parts['local_interwiki'];
3144 $this->mNamespace
= $parts['namespace'];
3145 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3147 $this->mDbkeyform
= $parts['dbkey'];
3148 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3149 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3151 # We already know that some pages won't be in the database!
3152 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3153 $this->mArticleID
= 0;
3160 * Get an array of Title objects linking to this Title
3161 * Also stores the IDs in the link cache.
3163 * WARNING: do not use this function on arbitrary user-supplied titles!
3164 * On heavily-used templates it will max out the memory.
3166 * @param array $options May be FOR UPDATE
3167 * @param string $table Table name
3168 * @param string $prefix Fields prefix
3169 * @return Title[] Array of Title objects linking here
3171 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3172 if ( count( $options ) > 0 ) {
3173 $db = wfGetDB( DB_MASTER
);
3175 $db = wfGetDB( DB_REPLICA
);
3180 self
::getSelectFields(),
3182 "{$prefix}_from=page_id",
3183 "{$prefix}_namespace" => $this->mNamespace
,
3184 "{$prefix}_title" => $this->mDbkeyform
],
3190 if ( $res->numRows() ) {
3191 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3192 foreach ( $res as $row ) {
3193 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3195 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3196 $retVal[] = $titleObj;
3204 * Get an array of Title objects using this Title as a template
3205 * Also stores the IDs in the link cache.
3207 * WARNING: do not use this function on arbitrary user-supplied titles!
3208 * On heavily-used templates it will max out the memory.
3210 * @param array $options Query option to Database::select()
3211 * @return Title[] Array of Title the Title objects linking here
3213 public function getTemplateLinksTo( $options = [] ) {
3214 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3218 * Get an array of Title objects linked from this Title
3219 * Also stores the IDs in the link cache.
3221 * WARNING: do not use this function on arbitrary user-supplied titles!
3222 * On heavily-used templates it will max out the memory.
3224 * @param array $options Query option to Database::select()
3225 * @param string $table Table name
3226 * @param string $prefix Fields prefix
3227 * @return array Array of Title objects linking here
3229 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3230 $id = $this->getArticleID();
3232 # If the page doesn't exist; there can't be any link from this page
3237 $db = wfGetDB( DB_REPLICA
);
3239 $blNamespace = "{$prefix}_namespace";
3240 $blTitle = "{$prefix}_title";
3242 $pageQuery = WikiPage
::getQueryInfo();
3244 [ $table, 'nestpage' => $pageQuery['tables'] ],
3246 [ $blNamespace, $blTitle ],
3247 $pageQuery['fields']
3249 [ "{$prefix}_from" => $id ],
3254 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3255 ] ] +
$pageQuery['joins']
3259 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3260 foreach ( $res as $row ) {
3261 if ( $row->page_id
) {
3262 $titleObj = self
::newFromRow( $row );
3264 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3265 $linkCache->addBadLinkObj( $titleObj );
3267 $retVal[] = $titleObj;
3274 * Get an array of Title objects used on this Title as a template
3275 * Also stores the IDs in the link cache.
3277 * WARNING: do not use this function on arbitrary user-supplied titles!
3278 * On heavily-used templates it will max out the memory.
3280 * @param array $options May be FOR UPDATE
3281 * @return Title[] Array of Title the Title objects used here
3283 public function getTemplateLinksFrom( $options = [] ) {
3284 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3288 * Get an array of Title objects referring to non-existent articles linked
3291 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3292 * should use redirect table in this case).
3293 * @return Title[] Array of Title the Title objects
3295 public function getBrokenLinksFrom() {
3296 if ( $this->getArticleID() == 0 ) {
3297 # All links from article ID 0 are false positives
3301 $dbr = wfGetDB( DB_REPLICA
);
3302 $res = $dbr->select(
3303 [ 'page', 'pagelinks' ],
3304 [ 'pl_namespace', 'pl_title' ],
3306 'pl_from' => $this->getArticleID(),
3307 'page_namespace IS NULL'
3313 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3319 foreach ( $res as $row ) {
3320 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3326 * Get a list of URLs to purge from the CDN cache when this
3329 * @return string[] Array of String the URLs
3331 public function getCdnUrls() {
3333 $this->getInternalURL(),
3334 $this->getInternalURL( 'action=history' )
3337 $pageLang = $this->getPageLanguage();
3338 if ( $pageLang->hasVariants() ) {
3339 $variants = $pageLang->getVariants();
3340 foreach ( $variants as $vCode ) {
3341 $urls[] = $this->getInternalURL( $vCode );
3345 // If we are looking at a css/js user subpage, purge the action=raw.
3346 if ( $this->isUserJsConfigPage() ) {
3347 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3348 } elseif ( $this->isUserJsonConfigPage() ) {
3349 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3350 } elseif ( $this->isUserCssConfigPage() ) {
3351 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3354 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3359 * Purge all applicable CDN URLs
3361 public function purgeSquid() {
3362 DeferredUpdates
::addUpdate(
3363 new CdnCacheUpdate( $this->getCdnUrls() ),
3364 DeferredUpdates
::PRESEND
3369 * Check whether a given move operation would be valid.
3370 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3372 * @deprecated since 1.25, use MovePage's methods instead
3373 * @param Title &$nt The new title
3374 * @param bool $auth Whether to check user permissions (uses $wgUser)
3375 * @param string $reason Is the log summary of the move, used for spam checking
3376 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3378 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3381 if ( !( $nt instanceof Title
) ) {
3382 // Normally we'd add this to $errors, but we'll get
3383 // lots of syntax errors if $nt is not an object
3384 return [ [ 'badtitletext' ] ];
3387 $mp = new MovePage( $this, $nt );
3388 $errors = $mp->isValidMove()->getErrorsArray();
3390 $errors = wfMergeErrorArrays(
3392 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3396 return $errors ?
: true;
3400 * Move a title to a new location
3402 * @deprecated since 1.25, use the MovePage class instead
3403 * @param Title &$nt The new title
3404 * @param bool $auth Indicates whether $wgUser's permissions
3406 * @param string $reason The reason for the move
3407 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3408 * Ignored if the user doesn't have the suppressredirect right.
3409 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3410 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3412 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3413 array $changeTags = []
3416 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3417 if ( is_array( $err ) ) {
3418 // Auto-block user's IP if the account was "hard" blocked
3419 $wgUser->spreadAnyEditBlock();
3422 // Check suppressredirect permission
3423 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3424 $createRedirect = true;
3427 $mp = new MovePage( $this, $nt );
3428 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3429 if ( $status->isOK() ) {
3432 return $status->getErrorsArray();
3437 * Move this page's subpages to be subpages of $nt
3439 * @param Title $nt Move target
3440 * @param bool $auth Whether $wgUser's permissions should be checked
3441 * @param string $reason The reason for the move
3442 * @param bool $createRedirect Whether to create redirects from the old subpages to
3443 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3444 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3445 * @return array Array with old page titles as keys, and strings (new page titles) or
3446 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3447 * getUserPermissionsErrors()-like error array with numeric indices if
3448 * no pages were moved
3450 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3451 array $changeTags = []
3453 global $wgMaximumMovedPages;
3454 // Check permissions
3455 if ( !$this->userCan( 'move-subpages' ) ) {
3457 [ 'cant-move-subpages' ],
3460 // Do the source and target namespaces support subpages?
3461 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3463 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
3466 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3468 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3472 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3475 foreach ( $subpages as $oldSubpage ) {
3477 if ( $count > $wgMaximumMovedPages ) {
3478 $retval[$oldSubpage->getPrefixedText()] = [
3479 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3484 // We don't know whether this function was called before
3485 // or after moving the root page, so check both
3487 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3488 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3490 // When moving a page to a subpage of itself,
3491 // don't move it twice
3494 $newPageName = preg_replace(
3495 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
3496 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3497 $oldSubpage->getDBkey() );
3498 if ( $oldSubpage->isTalkPage() ) {
3499 $newNs = $nt->getTalkPage()->getNamespace();
3501 $newNs = $nt->getSubjectPage()->getNamespace();
3503 # T16385: we need makeTitleSafe because the new page names may
3504 # be longer than 255 characters.
3505 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3507 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3508 if ( $success === true ) {
3509 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3511 $retval[$oldSubpage->getPrefixedText()] = $success;
3518 * Checks if this page is just a one-rev redirect.
3519 * Adds lock, so don't use just for light purposes.
3523 public function isSingleRevRedirect() {
3524 global $wgContentHandlerUseDB;
3526 $dbw = wfGetDB( DB_MASTER
);
3529 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3530 if ( $wgContentHandlerUseDB ) {
3531 $fields[] = 'page_content_model';
3534 $row = $dbw->selectRow( 'page',
3540 # Cache some fields we may want
3541 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3542 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3543 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3544 $this->mContentModel
= $row && isset( $row->page_content_model
)
3545 ?
strval( $row->page_content_model
)
3548 if ( !$this->mRedirect
) {
3551 # Does the article have a history?
3552 $row = $dbw->selectField( [ 'page', 'revision' ],
3554 [ 'page_namespace' => $this->mNamespace
,
3555 'page_title' => $this->mDbkeyform
,
3557 'page_latest != rev_id'
3562 # Return true if there was no history
3563 return ( $row === false );
3567 * Checks if $this can be moved to a given Title
3568 * - Selects for update, so don't call it unless you mean business
3570 * @deprecated since 1.25, use MovePage's methods instead
3571 * @param Title $nt The new title to check
3574 public function isValidMoveTarget( $nt ) {
3575 # Is it an existing file?
3576 if ( $nt->getNamespace() == NS_FILE
) {
3577 $file = wfLocalFile( $nt );
3578 $file->load( File
::READ_LATEST
);
3579 if ( $file->exists() ) {
3580 wfDebug( __METHOD__
. ": file exists\n" );
3584 # Is it a redirect with no history?
3585 if ( !$nt->isSingleRevRedirect() ) {
3586 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3589 # Get the article text
3590 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3591 if ( !is_object( $rev ) ) {
3594 $content = $rev->getContent();
3595 # Does the redirect point to the source?
3596 # Or is it a broken self-redirect, usually caused by namespace collisions?
3597 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3599 if ( $redirTitle ) {
3600 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3601 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3602 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3608 # Fail safe (not a redirect after all. strange.)
3609 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3610 " is a redirect, but it doesn't contain a valid redirect.\n" );
3616 * Get categories to which this Title belongs and return an array of
3617 * categories' names.
3619 * @return array Array of parents in the form:
3620 * $parent => $currentarticle
3622 public function getParentCategories() {
3625 $titleKey = $this->getArticleID();
3627 if ( $titleKey === 0 ) {
3631 $dbr = wfGetDB( DB_REPLICA
);
3633 $res = $dbr->select(
3636 [ 'cl_from' => $titleKey ],
3640 if ( $res->numRows() > 0 ) {
3641 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3642 foreach ( $res as $row ) {
3643 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3644 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3645 $this->getFullText();
3652 * Get a tree of parent categories
3654 * @param array $children Array with the children in the keys, to check for circular refs
3655 * @return array Tree of parent categories
3657 public function getParentCategoryTree( $children = [] ) {
3659 $parents = $this->getParentCategories();
3662 foreach ( $parents as $parent => $current ) {
3663 if ( array_key_exists( $parent, $children ) ) {
3664 # Circular reference
3665 $stack[$parent] = [];
3667 $nt = self
::newFromText( $parent );
3669 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3679 * Get an associative array for selecting this title from
3682 * @return array Array suitable for the $where parameter of DB::select()
3684 public function pageCond() {
3685 if ( $this->mArticleID
> 0 ) {
3686 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3687 return [ 'page_id' => $this->mArticleID
];
3689 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3694 * Get next/previous revision ID relative to another revision ID
3695 * @param int $revId Revision ID. Get the revision that was before this one.
3696 * @param int $flags Title::GAID_FOR_UPDATE
3697 * @param string $dir 'next' or 'prev'
3698 * @return int|bool New revision ID, or false if none exists
3700 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3701 $revId = (int)$revId;
3702 if ( $dir === 'next' ) {
3705 } elseif ( $dir === 'prev' ) {
3709 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
3712 if ( $flags & self
::GAID_FOR_UPDATE
) {
3713 $db = wfGetDB( DB_MASTER
);
3715 $db = wfGetDB( DB_REPLICA
, 'contributions' );
3718 // Intentionally not caring if the specified revision belongs to this
3719 // page. We only care about the timestamp.
3720 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
3721 if ( $ts === false ) {
3722 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
3723 if ( $ts === false ) {
3724 // Or should this throw an InvalidArgumentException or something?
3728 $ts = $db->addQuotes( $ts );
3730 $revId = $db->selectField( 'revision', 'rev_id',
3732 'rev_page' => $this->getArticleID( $flags ),
3733 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
3737 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
3738 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
3742 if ( $revId === false ) {
3745 return intval( $revId );
3750 * Get the revision ID of the previous revision
3752 * @param int $revId Revision ID. Get the revision that was before this one.
3753 * @param int $flags Title::GAID_FOR_UPDATE
3754 * @return int|bool Old revision ID, or false if none exists
3756 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3757 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3761 * Get the revision ID of the next revision
3763 * @param int $revId Revision ID. Get the revision that was after this one.
3764 * @param int $flags Title::GAID_FOR_UPDATE
3765 * @return int|bool Next revision ID, or false if none exists
3767 public function getNextRevisionID( $revId, $flags = 0 ) {
3768 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3772 * Get the first revision of the page
3774 * @param int $flags Title::GAID_FOR_UPDATE
3775 * @return Revision|null If page doesn't exist
3777 public function getFirstRevision( $flags = 0 ) {
3778 $pageId = $this->getArticleID( $flags );
3780 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3781 $revQuery = Revision
::getQueryInfo();
3782 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3783 [ 'rev_page' => $pageId ],
3786 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3787 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3792 return new Revision( $row, 0, $this );
3799 * Get the oldest revision timestamp of this page
3801 * @param int $flags Title::GAID_FOR_UPDATE
3802 * @return string|null MW timestamp
3804 public function getEarliestRevTime( $flags = 0 ) {
3805 $rev = $this->getFirstRevision( $flags );
3806 return $rev ?
$rev->getTimestamp() : null;
3810 * Check if this is a new page
3814 public function isNewPage() {
3815 $dbr = wfGetDB( DB_REPLICA
);
3816 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3820 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3824 public function isBigDeletion() {
3825 global $wgDeleteRevisionsLimit;
3827 if ( !$wgDeleteRevisionsLimit ) {
3831 if ( $this->mIsBigDeletion
=== null ) {
3832 $dbr = wfGetDB( DB_REPLICA
);
3834 $revCount = $dbr->selectRowCount(
3837 [ 'rev_page' => $this->getArticleID() ],
3839 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3842 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3845 return $this->mIsBigDeletion
;
3849 * Get the approximate revision count of this page.
3853 public function estimateRevisionCount() {
3854 if ( !$this->exists() ) {
3858 if ( $this->mEstimateRevisions
=== null ) {
3859 $dbr = wfGetDB( DB_REPLICA
);
3860 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3861 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3864 return $this->mEstimateRevisions
;
3868 * Get the number of revisions between the given revision.
3869 * Used for diffs and other things that really need it.
3871 * @param int|Revision $old Old revision or rev ID (first before range)
3872 * @param int|Revision $new New revision or rev ID (first after range)
3873 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3874 * @return int Number of revisions between these revisions.
3876 public function countRevisionsBetween( $old, $new, $max = null ) {
3877 if ( !( $old instanceof Revision
) ) {
3878 $old = Revision
::newFromTitle( $this, (int)$old );
3880 if ( !( $new instanceof Revision
) ) {
3881 $new = Revision
::newFromTitle( $this, (int)$new );
3883 if ( !$old ||
!$new ) {
3884 return 0; // nothing to compare
3886 $dbr = wfGetDB( DB_REPLICA
);
3888 'rev_page' => $this->getArticleID(),
3889 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3890 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3892 if ( $max !== null ) {
3893 return $dbr->selectRowCount( 'revision', '1',
3896 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3899 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3904 * Get the authors between the given revisions or revision IDs.
3905 * Used for diffs and other things that really need it.
3909 * @param int|Revision $old Old revision or rev ID (first before range by default)
3910 * @param int|Revision $new New revision or rev ID (first after range by default)
3911 * @param int $limit Maximum number of authors
3912 * @param string|array $options (Optional): Single option, or an array of options:
3913 * 'include_old' Include $old in the range; $new is excluded.
3914 * 'include_new' Include $new in the range; $old is excluded.
3915 * 'include_both' Include both $old and $new in the range.
3916 * Unknown option values are ignored.
3917 * @return array|null Names of revision authors in the range; null if not both revisions exist
3919 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3920 if ( !( $old instanceof Revision
) ) {
3921 $old = Revision
::newFromTitle( $this, (int)$old );
3923 if ( !( $new instanceof Revision
) ) {
3924 $new = Revision
::newFromTitle( $this, (int)$new );
3926 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3927 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3928 // in the sanity check below?
3929 if ( !$old ||
!$new ) {
3930 return null; // nothing to compare
3935 $options = (array)$options;
3936 if ( in_array( 'include_old', $options ) ) {
3939 if ( in_array( 'include_new', $options ) ) {
3942 if ( in_array( 'include_both', $options ) ) {
3946 // No DB query needed if $old and $new are the same or successive revisions:
3947 if ( $old->getId() === $new->getId() ) {
3948 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3950 [ $old->getUserText( Revision
::RAW
) ];
3951 } elseif ( $old->getId() === $new->getParentId() ) {
3952 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3953 $authors[] = $old->getUserText( Revision
::RAW
);
3954 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3955 $authors[] = $new->getUserText( Revision
::RAW
);
3957 } elseif ( $old_cmp === '>=' ) {
3958 $authors[] = $old->getUserText( Revision
::RAW
);
3959 } elseif ( $new_cmp === '<=' ) {
3960 $authors[] = $new->getUserText( Revision
::RAW
);
3964 $dbr = wfGetDB( DB_REPLICA
);
3965 $revQuery = Revision
::getQueryInfo();
3966 $authors = $dbr->selectFieldValues(
3967 $revQuery['tables'],
3968 $revQuery['fields']['rev_user_text'],
3970 'rev_page' => $this->getArticleID(),
3971 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3972 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3974 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3981 * Get the number of authors between the given revisions or revision IDs.
3982 * Used for diffs and other things that really need it.
3984 * @param int|Revision $old Old revision or rev ID (first before range by default)
3985 * @param int|Revision $new New revision or rev ID (first after range by default)
3986 * @param int $limit Maximum number of authors
3987 * @param string|array $options (Optional): Single option, or an array of options:
3988 * 'include_old' Include $old in the range; $new is excluded.
3989 * 'include_new' Include $new in the range; $old is excluded.
3990 * 'include_both' Include both $old and $new in the range.
3991 * Unknown option values are ignored.
3992 * @return int Number of revision authors in the range; zero if not both revisions exist
3994 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3995 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3996 return $authors ?
count( $authors ) : 0;
4000 * Compare with another title.
4002 * @param Title $title
4005 public function equals( Title
$title ) {
4006 // Note: === is necessary for proper matching of number-like titles.
4007 return $this->mInterwiki
=== $title->mInterwiki
4008 && $this->mNamespace
== $title->mNamespace
4009 && $this->mDbkeyform
=== $title->mDbkeyform
;
4013 * Check if this title is a subpage of another title
4015 * @param Title $title
4018 public function isSubpageOf( Title
$title ) {
4019 return $this->mInterwiki
=== $title->mInterwiki
4020 && $this->mNamespace
== $title->mNamespace
4021 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4025 * Check if page exists. For historical reasons, this function simply
4026 * checks for the existence of the title in the page table, and will
4027 * thus return false for interwiki links, special pages and the like.
4028 * If you want to know if a title can be meaningfully viewed, you should
4029 * probably call the isKnown() method instead.
4031 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4032 * from master/for update
4035 public function exists( $flags = 0 ) {
4036 $exists = $this->getArticleID( $flags ) != 0;
4037 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4042 * Should links to this title be shown as potentially viewable (i.e. as
4043 * "bluelinks"), even if there's no record by this title in the page
4046 * This function is semi-deprecated for public use, as well as somewhat
4047 * misleadingly named. You probably just want to call isKnown(), which
4048 * calls this function internally.
4050 * (ISSUE: Most of these checks are cheap, but the file existence check
4051 * can potentially be quite expensive. Including it here fixes a lot of
4052 * existing code, but we might want to add an optional parameter to skip
4053 * it and any other expensive checks.)
4057 public function isAlwaysKnown() {
4061 * Allows overriding default behavior for determining if a page exists.
4062 * If $isKnown is kept as null, regular checks happen. If it's
4063 * a boolean, this value is returned by the isKnown method.
4067 * @param Title $title
4068 * @param bool|null $isKnown
4070 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4072 if ( !is_null( $isKnown ) ) {
4076 if ( $this->isExternal() ) {
4077 return true; // any interwiki link might be viewable, for all we know
4080 switch ( $this->mNamespace
) {
4083 // file exists, possibly in a foreign repo
4084 return (bool)wfFindFile( $this );
4086 // valid special page
4087 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4088 exists( $this->mDbkeyform
);
4090 // selflink, possibly with fragment
4091 return $this->mDbkeyform
== '';
4093 // known system message
4094 return $this->hasSourceText() !== false;
4101 * Does this title refer to a page that can (or might) be meaningfully
4102 * viewed? In particular, this function may be used to determine if
4103 * links to the title should be rendered as "bluelinks" (as opposed to
4104 * "redlinks" to non-existent pages).
4105 * Adding something else to this function will cause inconsistency
4106 * since LinkHolderArray calls isAlwaysKnown() and does its own
4107 * page existence check.
4111 public function isKnown() {
4112 return $this->isAlwaysKnown() ||
$this->exists();
4116 * Does this page have source text?
4120 public function hasSourceText() {
4121 if ( $this->exists() ) {
4125 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4126 // If the page doesn't exist but is a known system message, default
4127 // message content will be displayed, same for language subpages-
4128 // Use always content language to avoid loading hundreds of languages
4129 // to get the link color.
4130 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4131 list( $name, ) = MessageCache
::singleton()->figureMessage(
4132 $contLang->lcfirst( $this->getText() )
4134 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4135 return $message->exists();
4142 * Get the default (plain) message contents for an page that overrides an
4143 * interface message key.
4145 * Primary use cases:
4148 * - Show default when viewing the page. The Article::getSubstituteContent
4149 * method displays the default message content, instead of the
4150 * 'noarticletext' placeholder message normally used.
4153 * - Title of edit page. When creating an interface message override,
4154 * the editor is told they are "Editing the page", instead of
4155 * "Creating the page". (EditPage::setHeaders)
4156 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4157 * or editing a an interface message override. (EditPage::showIntro)
4158 * - Opening the editor. The contents of the localisation message are used
4159 * as contents of the editor when creating a new page in the MediaWiki
4160 * namespace. This simplifies the process for editors when "changing"
4161 * an interface message by creating an override. (EditPage::getContentObject)
4162 * - Showing a diff. The left-hand side of a diff when an editor is
4163 * previewing their changes before saving the creation of a page in the
4164 * MediaWiki namespace. (EditPage::showDiff)
4165 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4166 * page with the proposed content matching the interface message default,
4167 * the save is rejected, the same way we disallow blank pages from being
4168 * created. (EditPage::internalAttemptSave)
4171 * - Default content, when using the 'prepend' or 'append' feature.
4174 * - Label the create action as "Edit", if the page can be an override.
4176 * @return string|bool
4178 public function getDefaultMessageText() {
4179 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4183 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4184 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4186 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4188 if ( $message->exists() ) {
4189 return $message->plain();
4196 * Updates page_touched for this page; called from LinksUpdate.php
4198 * @param string|null $purgeTime [optional] TS_MW timestamp
4199 * @return bool True if the update succeeded
4201 public function invalidateCache( $purgeTime = null ) {
4202 if ( wfReadOnly() ) {
4204 } elseif ( $this->mArticleID
=== 0 ) {
4205 return true; // avoid gap locking if we know it's not there
4208 $dbw = wfGetDB( DB_MASTER
);
4209 $dbw->onTransactionPreCommitOrIdle(
4210 function () use ( $dbw ) {
4211 ResourceLoaderWikiModule
::invalidateModuleCache(
4212 $this, null, null, $dbw->getDomainID() );
4217 $conds = $this->pageCond();
4218 DeferredUpdates
::addUpdate(
4219 new AutoCommitUpdate(
4222 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4223 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4226 [ 'page_touched' => $dbTimestamp ],
4227 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4230 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4233 DeferredUpdates
::PRESEND
4240 * Update page_touched timestamps and send CDN purge messages for
4241 * pages linking to this title. May be sent to the job queue depending
4242 * on the number of links. Typically called on create and delete.
4244 public function touchLinks() {
4245 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4246 if ( $this->mNamespace
== NS_CATEGORY
) {
4247 DeferredUpdates
::addUpdate(
4248 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4254 * Get the last touched timestamp
4256 * @param IDatabase|null $db
4257 * @return string|false Last-touched timestamp
4259 public function getTouched( $db = null ) {
4260 if ( $db === null ) {
4261 $db = wfGetDB( DB_REPLICA
);
4263 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4268 * Get the timestamp when this page was updated since the user last saw it.
4270 * @param User|null $user
4271 * @return string|null
4273 public function getNotificationTimestamp( $user = null ) {
4276 // Assume current user if none given
4280 // Check cache first
4281 $uid = $user->getId();
4285 // avoid isset here, as it'll return false for null entries
4286 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4287 return $this->mNotificationTimestamp
[$uid];
4289 // Don't cache too much!
4290 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4291 $this->mNotificationTimestamp
= [];
4294 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4295 $watchedItem = $store->getWatchedItem( $user, $this );
4296 if ( $watchedItem ) {
4297 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4299 $this->mNotificationTimestamp
[$uid] = false;
4302 return $this->mNotificationTimestamp
[$uid];
4306 * Generate strings used for xml 'id' names in monobook tabs
4308 * @param string $prepend Defaults to 'nstab-'
4309 * @return string XML 'id' name
4311 public function getNamespaceKey( $prepend = 'nstab-' ) {
4312 // Gets the subject namespace of this title
4313 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4314 // Prefer canonical namespace name for HTML IDs
4315 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4316 if ( $namespaceKey === false ) {
4317 // Fallback to localised text
4318 $namespaceKey = $this->getSubjectNsText();
4320 // Makes namespace key lowercase
4321 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4323 if ( $namespaceKey == '' ) {
4324 $namespaceKey = 'main';
4326 // Changes file to image for backwards compatibility
4327 if ( $namespaceKey == 'file' ) {
4328 $namespaceKey = 'image';
4330 return $prepend . $namespaceKey;
4334 * Get all extant redirects to this Title
4336 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4337 * @return Title[] Array of Title redirects to this title
4339 public function getRedirectsHere( $ns = null ) {
4342 $dbr = wfGetDB( DB_REPLICA
);
4344 'rd_namespace' => $this->mNamespace
,
4345 'rd_title' => $this->mDbkeyform
,
4348 if ( $this->isExternal() ) {
4349 $where['rd_interwiki'] = $this->mInterwiki
;
4351 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4353 if ( !is_null( $ns ) ) {
4354 $where['page_namespace'] = $ns;
4357 $res = $dbr->select(
4358 [ 'redirect', 'page' ],
4359 [ 'page_namespace', 'page_title' ],
4364 foreach ( $res as $row ) {
4365 $redirs[] = self
::newFromRow( $row );
4371 * Check if this Title is a valid redirect target
4375 public function isValidRedirectTarget() {
4376 global $wgInvalidRedirectTargets;
4378 if ( $this->isSpecialPage() ) {
4379 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4380 if ( $this->isSpecial( 'Userlogout' ) ) {
4384 foreach ( $wgInvalidRedirectTargets as $target ) {
4385 if ( $this->isSpecial( $target ) ) {
4395 * Get a backlink cache object
4397 * @return BacklinkCache
4399 public function getBacklinkCache() {
4400 return BacklinkCache
::get( $this );
4404 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4408 public function canUseNoindex() {
4409 global $wgExemptFromUserRobotsControl;
4411 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
4413 return !in_array( $this->mNamespace
, $bannedNamespaces );
4417 * Returns the raw sort key to be used for categories, with the specified
4418 * prefix. This will be fed to Collation::getSortKey() to get a
4419 * binary sortkey that can be used for actual sorting.
4421 * @param string $prefix The prefix to be used, specified using
4422 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4426 public function getCategorySortkey( $prefix = '' ) {
4427 $unprefixed = $this->getText();
4429 // Anything that uses this hook should only depend
4430 // on the Title object passed in, and should probably
4431 // tell the users to run updateCollations.php --force
4432 // in order to re-sort existing category relations.
4433 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4434 if ( $prefix !== '' ) {
4435 # Separate with a line feed, so the unprefixed part is only used as
4436 # a tiebreaker when two pages have the exact same prefix.
4437 # In UCA, tab is the only character that can sort above LF
4438 # so we strip both of them from the original prefix.
4439 $prefix = strtr( $prefix, "\n\t", ' ' );
4440 return "$prefix\n$unprefixed";
4446 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4447 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4448 * the db, it will return NULL.
4450 * @return string|null|bool
4452 private function getDbPageLanguageCode() {
4453 global $wgPageLanguageUseDB;
4455 // check, if the page language could be saved in the database, and if so and
4456 // the value is not requested already, lookup the page language using LinkCache
4457 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4458 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4459 $linkCache->addLinkObj( $this );
4460 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4463 return $this->mDbPageLanguage
;
4467 * Get the language in which the content of this page is written in
4468 * wikitext. Defaults to content language, but in certain cases it can be
4469 * e.g. $wgLang (such as special pages, which are in the user language).
4474 public function getPageLanguage() {
4475 global $wgLang, $wgLanguageCode;
4476 if ( $this->isSpecialPage() ) {
4477 // special pages are in the user language
4481 // Checking if DB language is set
4482 $dbPageLanguage = $this->getDbPageLanguageCode();
4483 if ( $dbPageLanguage ) {
4484 return wfGetLangObj( $dbPageLanguage );
4487 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4488 // Note that this may depend on user settings, so the cache should
4489 // be only per-request.
4490 // NOTE: ContentHandler::getPageLanguage() may need to load the
4491 // content to determine the page language!
4492 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4494 $contentHandler = ContentHandler
::getForTitle( $this );
4495 $langObj = $contentHandler->getPageLanguage( $this );
4496 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4498 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4505 * Get the language in which the content of this page is written when
4506 * viewed by user. Defaults to content language, but in certain cases it can be
4507 * e.g. $wgLang (such as special pages, which are in the user language).
4512 public function getPageViewLanguage() {
4515 if ( $this->isSpecialPage() ) {
4516 // If the user chooses a variant, the content is actually
4517 // in a language whose code is the variant code.
4518 $variant = $wgLang->getPreferredVariant();
4519 if ( $wgLang->getCode() !== $variant ) {
4520 return Language
::factory( $variant );
4526 // Checking if DB language is set
4527 $dbPageLanguage = $this->getDbPageLanguageCode();
4528 if ( $dbPageLanguage ) {
4529 $pageLang = wfGetLangObj( $dbPageLanguage );
4530 $variant = $pageLang->getPreferredVariant();
4531 if ( $pageLang->getCode() !== $variant ) {
4532 $pageLang = Language
::factory( $variant );
4538 // @note Can't be cached persistently, depends on user settings.
4539 // @note ContentHandler::getPageViewLanguage() may need to load the
4540 // content to determine the page language!
4541 $contentHandler = ContentHandler
::getForTitle( $this );
4542 $pageLang = $contentHandler->getPageViewLanguage( $this );
4547 * Get a list of rendered edit notices for this page.
4549 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4550 * they will already be wrapped in paragraphs.
4553 * @param int $oldid Revision ID that's being edited
4556 public function getEditNotices( $oldid = 0 ) {
4559 // Optional notice for the entire namespace
4560 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4561 $msg = wfMessage( $editnotice_ns );
4562 if ( $msg->exists() ) {
4563 $html = $msg->parseAsBlock();
4564 // Edit notices may have complex logic, but output nothing (T91715)
4565 if ( trim( $html ) !== '' ) {
4566 $notices[$editnotice_ns] = Html
::rawElement(
4570 'mw-editnotice-namespace',
4571 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4578 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4579 // Optional notice for page itself and any parent page
4580 $editnotice_base = $editnotice_ns;
4581 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4582 $editnotice_base .= '-' . $part;
4583 $msg = wfMessage( $editnotice_base );
4584 if ( $msg->exists() ) {
4585 $html = $msg->parseAsBlock();
4586 if ( trim( $html ) !== '' ) {
4587 $notices[$editnotice_base] = Html
::rawElement(
4591 'mw-editnotice-base',
4592 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4600 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4601 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4602 $msg = wfMessage( $editnoticeText );
4603 if ( $msg->exists() ) {
4604 $html = $msg->parseAsBlock();
4605 if ( trim( $html ) !== '' ) {
4606 $notices[$editnoticeText] = Html
::rawElement(
4610 'mw-editnotice-page',
4611 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4619 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4626 public function __sleep() {
4634 'mDefaultNamespace',
4638 public function __wakeup() {
4639 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4640 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4641 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );